﻿using Net_SCADA;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WZXC_GBL_QUERY
{
    public class QueryOneDayData
    {

        //构造函数用来获取当前日期的数据，绘图时需要进行调用
        //需要添加一个完成绘图的事件。以便能够进行线程级别的绘图  OnPaintCompleted
        //添加载入数据的完成时间  OnLoadDataCompleted
        public DateTime QueryDate { get; set; }//需要查询的时间
        public Dictionary<int, float[]> LineData { get; set; }//存放当天的数据
        public string[] LineTime { get; set; }//上述点对应的时间
        public int YAxisHeight { get; set; } = 30;//曲线下方显示的时间文本
        public Font CurveFont { get; set; } = new Font("宋体", 9f, FontStyle.Regular);
        public Dictionary<int, PVMaxMin> PVMaxMinByDay { get; set; } = new Dictionary<int, PVMaxMin>();
        public bool isLoadDataCurrect { get; set; } = false;
        public PictureBox CurvePic = new PictureBox();


        private float _xScale = 1;
        private int CurveHeight = 100;



        //构造函数
        public QueryOneDayData(DateTime _querydate)
        {
            QueryDate = _querydate;
            //加载当前日期的数据，初始话的时候显示
        }

        //获取数据
        public bool GetOneDayData(List<Zone> lstzone)
        {
            isLoadDataCurrect = GetQueryData(QueryDate, QueryDate.AddDays(1).AddSeconds(-1), lstzone);
            return isLoadDataCurrect;
        }
        //获取曲线
        public Bitmap GetCurve(Size picCurveSize, List<int> lstZoneid, Dictionary<int, CurveSetting> dictLineSetting)
        {
            Bitmap bm = new Bitmap(picCurveSize.Width, picCurveSize.Height);
            try
            {
                _xScale = picCurveSize.Width / 2880f;
                DrawBackGround(bm);
                if (isLoadDataCurrect)
                {
                    DrawCurve(bm, lstZoneid, dictLineSetting);
                }
                else
                {
                    DrawNoData();
                }
                return bm;
            }
            catch (Exception)
            {
                return bm;
            }
        }


        private void DrawNoData()
        {
            Label lbl = new Label()
            {
                Font = new Font("微软雅黑", 12f, FontStyle.Regular),
                Text = "没有查找到当日数据",
                BorderStyle = BorderStyle.FixedSingle,
                TextAlign = ContentAlignment.MiddleCenter,
                ForeColor = Color.Red,
                Size = new Size(300, 100),
                Location = new Point(20, 20)
            };
            CurvePic.Controls.Add(lbl);
        }
        //这里对数据进行填充，需要时间的范围
        private bool GetQueryData(DateTime _stime, DateTime _etime, List<Zone> lstzone)
        {
            DataTable dt = DBOperate.GetParameterData(_stime, _etime);
            if (dt == null || dt.Rows.Count == 0) return false;
            initLineData(2880, lstzone);//一天的分钟数量*2,30秒一次数据
            LineTime = new string[2880];

            int totalqueryminutes = (int)_etime.Subtract(_stime).TotalMinutes;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DateTime edTime = Convert.ToDateTime(dt.Rows[i]["savetime"]);
                int minuteinterval = (int)edTime.Subtract(_stime).TotalMinutes;
                if (minuteinterval < 0 || minuteinterval > totalqueryminutes) continue;
                if (edTime.Second < 30)
                    LineTime[minuteinterval * 2] = edTime.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    LineTime[minuteinterval * 2+1] = edTime.ToString("yyyy-MM-dd HH:mm:ss");
            }

            foreach (var id in LineData.Keys)
            {
                if (LineData[id] != null) Array.Clear(LineData[id], 0, LineData[id].Length);
                //[id] = new float[totalqueryminutes];
                bool isHaveID = PVMaxMinByDay.ContainsKey(id);
                if (isHaveID)
                {
                    PVMaxMinByDay[id].min = 9999f;
                    PVMaxMinByDay[id].max = 0;
                    Zone z = lstzone.Find((v) => (v.pv != null && v.pv.ID == id));
                    PVMaxMinByDay[id].zonename = z == null ? "" : z.ZoneName;
                }
                if (!dt.Columns.Contains(id.ToString())) continue;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DateTime edTime = Convert.ToDateTime(dt.Rows[i]["savetime"]);
                    int minuteinterval = (int)edTime.Subtract(_stime).TotalMinutes;
                    if (minuteinterval < 0 || minuteinterval > totalqueryminutes) continue;
                    if (edTime.Second < 30)
                        LineData[id][minuteinterval * 2] = float.TryParse(dt.Rows[i][id.ToString()].ToString(), out float v) ? v : 0;
                    else
                        LineData[id][minuteinterval * 2 + 1] = float.TryParse(dt.Rows[i][id.ToString()].ToString(), out float v) ? v : 0;

                    if (isHaveID)//进行数据的统计
                    {
                        if (PVMaxMinByDay[id].max < LineData[id][minuteinterval])
                        {
                            PVMaxMinByDay[id].max = LineData[id][minuteinterval];
                            PVMaxMinByDay[id].maxtime = edTime;
                        }
                        if (PVMaxMinByDay[id].max < LineData[id][minuteinterval + 1])
                        {
                            PVMaxMinByDay[id].max = LineData[id][minuteinterval + 1];
                            PVMaxMinByDay[id].maxtime = edTime;
                        }
                        if (PVMaxMinByDay[id].min > LineData[id][minuteinterval])
                        {
                            PVMaxMinByDay[id].min = LineData[id][minuteinterval];
                            PVMaxMinByDay[id].mintime = edTime;
                        }
                        if (PVMaxMinByDay[id].min > LineData[id][minuteinterval + 1])
                        {
                            PVMaxMinByDay[id].min = LineData[id][minuteinterval + 1];
                            PVMaxMinByDay[id].mintime = edTime;
                        }
                    }
                }
            }
            return true;
        }
        private void initLineData(int totalminutes, List<Zone> _zone)
        {//显示天数据时的设置
            LineData = new Dictionary<int, float[]>();
            for (int i = 0; i < _zone.Count; i++)
            {
                if (_zone[i].isShowCurve)
                {
                    if (_zone[i].pv != null)
                    {
                        LineData.Add(_zone[i].pv.ID, new float[totalminutes]);
                        PVMaxMinByDay[_zone[i].pv.ID] = new PVMaxMin();
                    }
                    if (_zone[i].sv != null)
                    {
                        LineData.Add(_zone[i].sv.ID, new float[totalminutes]);
                    }
                    if (_zone[i].ovpv != null)
                    {
                        LineData.Add(_zone[i].ovpv.ID, new float[totalminutes]);
                    }
                }
            }
        }
        private void DrawCurve(Bitmap bm, List<int> lstZoneid, Dictionary<int, CurveSetting> dictLineSetting)
        {
            for (int i = 0; i < lstZoneid.Count; i++)
            {
                DrawOneCurve(bm, lstZoneid[i], dictLineSetting[lstZoneid[i]]);
            }
        }

        private void DrawOneCurve(Bitmap bm, int zoneID, CurveSetting lineSetting)
        {
            Pen p = new Pen(lineSetting.CurveColor, 1);
            Graphics g = Graphics.FromImage(bm);
            float x0, y0, x1, y1;
            x0 = 0;
            y0 = CurveHeight * (lineSetting.AxisMax - LineData[zoneID][0]) / (lineSetting.AxisMax - lineSetting.AxisMin);
            for (int j = 1; j < LineData[zoneID].Length; j++)
            {
                y1 = CurveHeight * (lineSetting.AxisMax - LineData[zoneID][j]) / (lineSetting.AxisMax - lineSetting.AxisMin);
                x1 = j * _xScale;
                //if (LineData[zoneID][j] * LineData[zoneID][j - 1] != 0)
                //{
                g.DrawLine(p, x0, y0, x1, y1);
                // }
                y0 = y1;
                x0 = x1;
            }
        }
        private void DrawBackGround(Bitmap bm)
        {

            if (bm.Width == 0 || bm.Height == 0) return;
            int h = bm.Height - YAxisHeight;
            int w = bm.Width;
            //画横向的线

            int smallDiv = h / 50;
            int bigDiv = smallDiv * 10;
            h = bigDiv * 5;
            CurveHeight = h;
            Graphics _g = Graphics.FromImage(bm);
            Pen p = new Pen(Color.Gray, 1);

            for (int i = 0; i < 5; i++)
            {
                p.Color = Color.DarkGray;
                _g.DrawLine(p, 0, i * bigDiv, w, i * bigDiv);
                p.Color = Color.LightGray;
                for (int j = 1; j < 10; j++)
                {
                    _g.DrawLine(p, 0, i * bigDiv + j * smallDiv, w, i * bigDiv + j * smallDiv);
                }
            }
            p.Color = Color.DarkGray;
            _g.DrawLine(p, 0, h, w, h);
            //画纵向的线
            SolidBrush brush = new SolidBrush(Color.Black);
            int xIndex = 0;
            int min = 0;
            SizeF sf;
            StringBuilder sb;
            while (xIndex * 120 < w)
            {
                p.Color = Color.DarkGray;
                _g.DrawLine(p, xIndex * 120, 0, xIndex * 120, h);
                min = (int)((xIndex * 60) / _xScale);
                //sb = new StringBuilder(xIndex.ToString("00") + ":00");
                sb = new StringBuilder().Append((min / 60).ToString("00")).Append(":").Append((min % 60).ToString("00"));
                sf = fdPublicFunction.GetTextSize(CurveFont, sb);
                _g.DrawString(sb.ToString(), CurveFont, brush, new PointF(xIndex * 120f - sf.Width / 2, h + 2));
                xIndex++;
            }
            _g.DrawLine(p, w - 1, 0, w - 1, h);//最后的一个线不绘制了。看效果
            _g.DrawString(QueryDate.ToString("yyyy-MM-dd HH:mm:00"), CurveFont, brush, new PointF(0, h + 14));
            //string s = QueryDate.AddMinutes(bm.Width / _xScale).ToString("yyyy-MM-dd HH:mm");
            //_g.DrawString(s, CurveFont, brush, new PointF(bm.Width - _g.MeasureString(s, CurveFont).Width + 2, h + 14));
        }
    }
}

